// pages/index/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp();
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //导航默认选中
    active: 'home',
    //是否开启搜索框浮动
    hideTop: false,
    openId: '',
    actions: [
      {
        name: '删除',
        color: '#fff',
        fontsize: '20',
        width: 100,
        icon: 'delete_fill',
        background: '#ed3f14'
      },
      {
        name: '返回',
        width: 100,
        color: '#80848f',
        fontsize: '20',
        icon: 'undo'
      }
    ],
    //备忘录列表
    memoList: [],
    // 加载数据相关
    page: 0,
    pageSize: 10,
    count: 0,
    //加载显示
    loadStatis: false,
    isLoad: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var openId = wx.getStorageSync('openId');
    //获取OpenId
    if (!openId) {
      getOpenId();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var page = 0;
    var pageSize = that.data.pageSize;
    var memoList = [];

    //获取备忘记录列表
    getMemoList(that, page, pageSize, memoList);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.onShow()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var page = that.data.page;
    var pageSize = that.data.pageSize;
    var memoList = that.data.memoList;
    that.setData({
      loadStatis: true,
      page: page + 1,
      isLoad: true
    })
    //获取备忘列表
    getMemoList(that, page + 1, pageSize, memoList);

  },

  //页面滚动监听
  onPageScroll: function ({ scrollTop }) {
    let that = this;
    if (scrollTop >= 54) {
      that.setData({
        hideTop: true
      })
    } else {
      that.setData({
        hideTop: false
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 设置分享标题
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },

  /**
   * 进入搜索备忘录页面
   */
  onSearchMemo: function () {
    wx.navigateTo({
      url: '/pages/searchMemo/index',
    })
  },

  /**
   * 进入修改/查看备忘页面
   */
  onUpdateMemo: function ({ currentTarget }) {
    const { memoid } = currentTarget.dataset;
    if (memoid) {
      wx.navigateTo({
        url: '/pages/editMemo/index?memoId=' + memoid,
      })
    } else {
      Toast('获取该备忘录信息为空')
    }
  },

  /**
   * 点击右侧按钮监听事件
   */
  onCloseButton: function ({ currentTarget, detail }) {
    var that = this;
    const { memoid } = currentTarget.dataset;
    const { title } = currentTarget.dataset;
    const index = detail.index;
    if (0 === index) {
      //等于0时为删除
      Dialog.confirm({
        title: '提醒',
        message: '您确定要删除【' + title + '】这条备注吗？'
      })
        .then(() => {
          //删除备忘信息
          deleteMemo(that, memoid);
        })
    }
  },

  /**
   * 切换导航
   * @param {*} res 
   */
  onChangeTabbar: function ({ detail }) {
    if ('add' === detail) {
      //跳转到添加页面
      wx.navigateTo({
        url: '/pages/addMemo/index',
      })
    } else if ('my' === detail) {
      //跳转到我的页面
      wx.navigateTo({
        url: '/pages/my/index',
      })
    }
  }
})


/**
 * 刪除备忘信息
 */
function deleteMemo(that, memoid) {
  db.collection(app.globalData.memoCollection).doc(memoid)
    .remove()
    .then(res => {
      var stats = res.stats;
      if (stats && stats.removed > 0) {
        that.onShow();
        Toast.loading({
          type: 'text',
          duration: 1500,
          message: "刪除成功"
        });
      }
    })
    .catch(error => {
      that.onShow();
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}


/**
 * 获取备忘记录列表
 */
function getMemoList(that, page, pageSize, memoList) {
  db.collection(app.globalData.memoCollection)
    .orderBy('status', 'ase') //先按照状态排序
    .orderBy('level', 'desc')//再按照等级排序
    .skip(page * pageSize)
    .limit(pageSize)
    .get().then(res => {
      // res.data 是一个包含集合中有权限访问的所有记录的数据，不超过 20 条
      console.log(res)
      // 数据成功后，停止下拉刷新
      wx.stopPullDownRefresh();
      if (res.data.length != 0) {
        that.setData({
          memoList: memoList.concat(res.data),
          page:page
        })
      } else {
        if (memoList.length >= 10) {
          that.setData({
            memoList: memoList.concat(res.data),
            loadStatis: true,
            isLoad: false
          })
        }else{
          // 不够10个不出现已加载全部
          that.setData({
            memoList: memoList.concat(res.data),
            loadStatis: false,
            isLoad: true
          })
        }
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    });
}

/**
 * 获取OpenId
 */
function getOpenId() {
  // 调用云函数
  wx.cloud.callFunction({
    name: 'login',
    data: {},
    success: res => {
      var openId = res.result.openid;
      app.globalData.openid = openId;
      wx.setStorageSync('openId', openId);
    },
    fail: err => {
      console.error('[云函数] [login] 调用失败', err)
    }
  })
}